<template>
  <view class="container">
    <view class="content">
      <view class="form-group">
        <text class="label">作业员ID</text>
        <view class="input-wrapper">
          <view class="input-container">
            <input 
              class="input" 
              type="text" 
              v-model="operatorId" 
              placeholder="请扫码输入作业员ID" 
              @confirm="onOperatorIdConfirm" 
              :focus="true" 
              confirm-type="done" 
              :cursor-spacing="0" 
              :adjust-position="false" 
              hold-keyboard="false" 
              inputmode="none" 
            />
            <view v-if="operatorId && operatorId.trim().length > 0" class="clear-btn" @click="onOperatorIdClear">
              <text class="clear-icon">×</text>
            </view>
          </view>
        </view>
      </view>
      
      <view class="form-group">
        <text class="label">作业员名</text>
        <view class="name-display">
          <text v-if="!loading && operatorName" class="name-text">{{ operatorName }}</text>
          <text v-else-if="loading" class="loading-text">加载中...</text>
        </view>
      </view>
    </view>
    
    <view class="button-group">
      <button class="btn btn-back" @click="onBack">返回</button>
      <button class="btn btn-start" @click="onStart" :disabled="!canStart">开始</button>
    </view>
  </view>
</template>

<script>
import { getWorkerInfo } from '@/api/worker.js';
import { saveOperatorConfirm } from '@/api/smt.js';
import { 
  setBaseCacheData,
  getBaseCacheData,
  updateBaseCacheData,
  clearAllCacheData,
  getCacheStatus
} from '@/utils/cacheManager.js';

export default {
  data() {
    return {
      operatorId: '',
      operatorName: '',
      orderNo: '',
      machineId: '',
      surface: '',
      pcbId: '',
      smtSide: '',
      mounterType: '',
      lineId: '',
      partList: [], // Add partList to store BOM items
      loading: false,
      hasError: false,
      errorMessage: '',
      cacheKey: '', // 存储缓存键
      confirmFailCount: 0, // 确认失败计数
      CONFIRM_FAIL_LIMIT: 3
    };
  },
  computed: {
    canStart() {
      return !this.loading && this.operatorName !== '';
    }
  },
  methods: {
    async fetchOperatorInfo(operatorId) {
      this.loading = true;
      this.hasError = false;
      this.errorMessage = '';
      
      try {
        const response = await getWorkerInfo(operatorId);
        
        if (response.statusCode === 200 && response.data && response.data.code === '00000') {
          // Business logic success
          this.operatorName = response.data.data; // data contains the worker name
          this.hasError = false;
        } else {
          // Business logic error - 使用toast显示错误信息
          this.operatorName = '';
          this.hasError = true;
          const errorMessage = response.data?.message || '获取作业员信息失败';
          uni.showToast({
            title: errorMessage,
            icon: 'none',
            duration: 2000
          });
        }
      } catch (error) {
        this.operatorName = '';
        this.hasError = true;
        const errorMessage = error.userMessage || '系统错误，请联系管理员';
        uni.showToast({
          title: errorMessage,
          icon: 'none',
          duration: 2000
        });
      } finally {
        this.loading = false;
      }
    },
    
    onBack() {
      uni.navigateBack();
    },
    
    onOperatorIdConfirm() {
      if (this.operatorId && this.operatorId.trim().length > 0) {
        this.fetchOperatorInfo(this.operatorId);
      }
    },
    
    // 原生清除按钮事件处理
    onOperatorIdClear() {
      this.operatorId = '';
      this.operatorName = '';
      this.hasError = false;
      this.errorMessage = '';
      this.loading = false;
    },
    
    async onStart() {
      if (this.canStart) {
        
        // 显示加载状态
        uni.showLoading({ 
          title: '保存中...',
          mask: true 
        });
        
        try {
          // 📋 使用双缓存系统获取当前基础数据
          const currentBaseData = getBaseCacheData();
          if (!currentBaseData) {
            uni.hideLoading();
            uni.showToast({
              title: '基础数据缺失，请重新开始',
              icon: 'none',
              duration: 2000
            });
            return;
          }
          
          console.log('📤 准备提交作业员确认数据:', currentBaseData);
          
          // 准备订单信息
          const orderInfo = {
            orderNo: currentBaseData.orderNo,
            orderBranchNo: currentBaseData.orderBranchNo || '01',
            mounterId: currentBaseData.mounterId,
            smtSide: currentBaseData.smtSide || this.surface || '1',
            operatorId: this.operatorId,
            lineId: currentBaseData.lineId
          };
          
          // 调用后端API保存作业员确认记录
          const response = await saveOperatorConfirm(orderInfo);
          
          if (response && response.statusCode === 200 && response.data && response.data.code === '00000') {
            
            console.log('✅ 作业员确认保存成功');
            
            // 🔄 更新基础缓存中的作业员信息
            const success = updateBaseCacheData({
              operatorId: this.operatorId,
              operatorName: this.operatorName
            });
            
            if (!success) {
              uni.hideLoading();
              uni.showToast({
                title: '数据缓存失败',
                icon: 'none',
                duration: 2000
              });
              return;
            }
            
            // 获取缓存状态信息
            const cacheStatus = getCacheStatus();
            console.log('📊 当前缓存状态:', cacheStatus);
            
            uni.hideLoading();
            
            // 跳转到 delivery-confirm 页面（使用纯双缓存系统）
            console.log('🚀 跳转到出库确认页面');
            uni.navigateTo({
              url: '/pages/delivery-confirm/delivery-confirm'
            });
            
          } else {
            uni.hideLoading();
            const errorMessage = (response && response.data && response.data.message) || '保存作业员确认记录失败';
            uni.showToast({
              title: errorMessage,
              icon: 'none',
              duration: 2000
            });
          }
        } catch (error) {
          uni.hideLoading();
          const userMessage = error.userMessage || 
                             error.message || 
                             '保存作业员确认记录失败，请重试';
          uni.showToast({
            title: userMessage,
            icon: 'none',
            duration: 2000
          });
          // 确认失败计数
          this.incrementConfirmFailCount();
        }
      }
    },
    
    // 确认失败计数（防止缓存堆积）
    incrementConfirmFailCount() {
      this.confirmFailCount++;
      if (this.confirmFailCount >= this.CONFIRM_FAIL_LIMIT) {
        console.warn(`确认失败超过${this.CONFIRM_FAIL_LIMIT}次，清理缓存`);
        this.clearCacheData();
        this.confirmFailCount = 0;
      }
    },
    
    // 清理缓存数据
    clearCacheData() {
      try {
        // 只清理失败累积的临时缓存，不清理BOM和作业员数据
        const { smartCleanupCaches } = require('@/utils/cacheManager');
        smartCleanupCaches(false); // 保留关键业务数据
        
        // 也移除当前页面的特定缓存
        if (this.cacheKey) {
          uni.removeStorageSync(decodeURIComponent(this.cacheKey));
          console.log('页面特定缓存已清理:', this.cacheKey);
        }
      } catch (error) {
        console.error('清理缓存失败:', error);
      }
    }
  },
  
  onUnload() {
    // 页面卸载时清理失败累积的缓存
    if (this.confirmFailCount > 0) {
      console.log('页面卸载，清理失败累积的缓存');
      this.clearCacheData();
    }
  },
  
  onLoad(options) {
    // 页面加载完成后设置焦点
    setTimeout(() => {
      this.$forceUpdate();
    }, 300);
    
    // 使用双缓存系统读取数据
    console.log('📥 作业员确认页面加载，读取基础缓存数据...');
    const baseData = getBaseCacheData();
    
    if (baseData) {
      console.log('✅ 成功读取基础缓存数据:', baseData);
      
      // 从基础缓存中读取数据
      this.orderNo = baseData.orderNo || '';
      this.machineId = baseData.mounterId || '';
      this.surface = baseData.smtSide || '';  
      this.lineId = baseData.lineId || '';
      this.partList = baseData.partList || [];
      
      console.log('📋 页面数据已设置:', {
        orderNo: this.orderNo,
        machineId: this.machineId,
        surface: this.surface,
        lineId: this.lineId,
        partCount: this.partList.length
      });
    } else {
      console.error('❌ 基础缓存数据不存在，请从程序选择页面重新开始');
      uni.showToast({
        title: '缺少基础数据，请重新开始',
        icon: 'none',
        duration: 2000
      });
      
      // 跳转回程序选择页面
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/select/select'
        });
      }, 2000);
    }
  }
};
</script>

<style>
.container {
  display: flex;
  flex-direction: column;
  height: calc(100vh - var(--window-top));
  background-color: #f2f2f2;
}

.header {
  background-color: #007AFF;
  padding: 20px 0;
  text-align: center;
}

.header-title {
  color: white;
  font-size: 18px;
  font-weight: bold;
}

.content {
  flex: 1;
  padding: 15px 20px;
  background-color: #f2f2f2;
}

.form-group {
  margin-bottom: 15px;
  width: 100%;
}

.label {
  display: block;
  margin-bottom: 5px;
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.input-wrapper {
  width: 100%;
}

.input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
  background-color: white;
  font-size: 16px;
  font-family: monospace;
  box-sizing: border-box;
  height: 40px;
}

/* 输入框容器和清除按钮样式 */
.input-container {
  position: relative;
  width: 100%;
}

.clear-btn {
  position: absolute;
  right: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 20px;
  height: 20px;
  background-color: #ccc;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
}

.clear-btn:hover {
  background-color: #999;
}

.clear-icon {
  color: white;
  font-size: 14px;
  font-weight: bold;
  line-height: 1;
}

.input.readonly {
  background-color: #f5f5f5;
  color: #333;
}


.name-display {
  padding: 8px 0;
  font-size: 18px;
  color: #333;
  min-height: 40px;
  display: flex;
  align-items: center;
  background-color: transparent;
}

.name-text {
  font-weight: bold;
  color: #333;
}

.loading-text {
  color: #666;
  font-style: italic;
}

.button-group {
  display: flex;
  justify-content: space-between;
  padding: 10px;
  background-color: #f2f2f2;
  flex-shrink: 0;
}

.btn {
  width: 48%; /* Adjusted for two buttons */
  height: 40px;
  border-radius: 6px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  font-weight: bold;
  cursor: pointer;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.2);
  transition: all 0.2s;
}

.btn:active {
  transform: translateY(2px);
  box-shadow: 0 1px 2px rgba(0,0,0,0.2);
}

.btn-back {
  background-color: #607D8B; /* 蓝灰色 - 低调的辅助功能 */
  color: white;
  border: 1px solid #546E7A;
}

.btn-back:hover {
  background-color: #546E7A;
  transform: translateY(1px);
}

.btn-back:active {
  background-color: #455A64;
  transform: translateY(2px);
}

.btn-start {
  background-color: #4CAF50;
  color: white;
}

.btn-start:disabled {
  background-color: #ccc;
  color: #999;
}
</style>